package com.ikingtech.framework.sdk.datasource.model.enums;

import com.ikingtech.framework.sdk.context.exception.FrameworkException;
import lombok.RequiredArgsConstructor;

/**
 * @author tie yan
 */
@RequiredArgsConstructor
public enum DatasourceSchemaTypeEnum {

    /**
     * Mysql
     */
    MYSQL("Mysql", "com.mysql.cj.jdbc.Driver", "jdbc:mysql://{}:{}/mysql?characterEncoding=utf8&allowMultiQueries=true&useSSL=false&serverTimezone=Asia/Shanghai"),

    /**
     * POSTGRES
     */
    POSTGRES("Postgres", "org.postgresql.Driver", "jdbc:postgresql://{}:{}?useSSL=false"),

    /**
     * ORACLE
     */
    ORACLE("Oracle", "oracle.jdbc.driver.OracleDriver", "jdbc:oracle:thin:@{}:{}"),

    /**
     * MSSQL_SERVER
     */
    MSSQL_SERVER("SQLServer", "com.microsoft.sqlserver.jdbc.SQLServerDriver", "jdbc:sqlserver://{}:{};");

    public final String description;

    public final String driverClassName;

    public final String jdbcUrl;

    public String jdbcUrl(String ip, String port) {
        if (MYSQL.equals(this)) {
            return "jdbc:mysql://" + ip + ":" + port + "?characterEncoding=utf8&allowMultiQueries=true&useSSL=false&serverTimezone=Asia/Shanghai";
        }
        if (POSTGRES.equals(this)) {
            return "jdbc:postgresql://" + ip + ":" + port + "?useSSL=false";
        }
        if (ORACLE.equals(this)) {
            return "jdbc:oracle:thin:@" + ip + ":" + port;
        }
        if (MSSQL_SERVER.equals(this)) {
            return "jdbc:sqlserver://" + ip + ":" + port + ";";
        }
        return null;
    }

    public static String parseHostByJdbcUrl(String databaseType, String jdbcUrl) {
        String urlWithoutPrefix = jdbcUrl.substring(jdbcUrl.indexOf("/") + 2);
        if (MYSQL.name().equals(databaseType)) {
            return urlWithoutPrefix.substring(0, urlWithoutPrefix.indexOf("/"));
        }
        if (POSTGRES.name().equals(databaseType)) {
            return urlWithoutPrefix.substring(0, urlWithoutPrefix.indexOf("?"));
        }
        if (ORACLE.name().equals(databaseType)) {
            return jdbcUrl.substring(jdbcUrl.indexOf("@") + 1);
        }
        if (MSSQL_SERVER.name().equals(databaseType)) {
            return urlWithoutPrefix;
        }
        return null;
    }

    public static DatasourceSchemaTypeEnum valueOfDriverClassName(String driverClassName) {
        for (DatasourceSchemaTypeEnum value : DatasourceSchemaTypeEnum.values()) {
            if (value.driverClassName.equals(driverClassName)) {
                return value;
            }
        }
        throw new FrameworkException("invalidDriverClassName");
    }
}
